package com.surprise.base.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;




/**
 * ReflectionUtils
 * @author nick
 * 2013-11-18
 */
@SuppressWarnings("unchecked")
public class ReflectionUtils {
    private static Log logger = LogFactory.getLog(ReflectionUtils.class);

    /**
     * 获得泛型类型
     * 
     * @param clazz
     * @return
     */
    public static Class getSuperClassGenricType(final Class clazz) {
        return getSuperClassGenricType(clazz, 0);
    }

    /**
     * 获得父类的参数泛型类型
     * 
     * @param clazz
     * @param index
     * @return
     */
    public static Class getSuperClassGenricType(final Class clazz,
            final int index) {
        Type genType = clazz.getGenericSuperclass();

        if (!(genType instanceof ParameterizedType)) {
            logger.warn(clazz.getSimpleName()
                    + "'s superclass not ParameterizedType");
            return Object.class;
        }

        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

        if (index >= params.length || index < 0) {
            logger.warn("Index: " + index + ", Size of "
                    + clazz.getSimpleName() + "'s Parameterized Type: "
                    + params.length);
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
            logger.warn(clazz.getSimpleName()
                    + " not set the actual class on superclass generic parameter");
            return Object.class;
        }

        return (Class) params[index];
    }

    public static Method getGetterMethod(Class c, String propertyName) {
        try {
            Method m = c.getMethod("get" + initStr(propertyName));
            return m;
        } catch (Exception e) {
            throw new RuntimeException("getter not found");
        }
    }

    public static Object getPropertyByName(Object obj, String propertyName)
            throws IllegalAccessException, InvocationTargetException,
            NoSuchMethodException {
        return org.apache.commons.beanutils.PropertyUtils.getProperty(obj,
                propertyName);
    }

    /**
     * 获得大小前字母
     * 
     * @param old
     * @return
     */
    public static String initStr(String old) {
        String str = old.substring(0, 1).toUpperCase() + old.substring(1);
        return str;
    }
}
